package com.hkbigdata.wordcount;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.*;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * @author liuanbo
 * @creat 2024-03-07-15:55
 * @see 2194550857@qq.com
 */
public class Flink001_WordCount_Batch {
    public static void main(String[] args) throws Exception {
        //1.数据准备，单词是以空格分隔
        //2.创建执行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();//alt+回车 返回变量

        //3.利用环境读取 hadoop spark kafka redis
        DataSource<String> stringDataSource = env.readTextFile("input/word.txt");//ctrl+p 查看参数

        //4.扁平化单词 匿名内部类kafka hadoop redis mysql java
        FlatMapOperator<String, String> stringStringFlatMapOperator = stringDataSource.flatMap(new MyFlatMap());

        //5.将单词映射成二元组(kafka,1) (hadoop,1) (java,1) (mysql,1)
        MapOperator<String, Tuple2<String, Integer>> map = stringStringFlatMapOperator.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                return new Tuple2<>(value, 1);
            }
        });

        //打印
        //map.print();
       //6.分组
        UnsortedGrouping<Tuple2<String, Integer>> tuple2UnsortedGrouping = map.groupBy(0);

        //7.聚合
        AggregateOperator<Tuple2<String, Integer>> sum = tuple2UnsortedGrouping.sum(1);

        //8.打印
        sum.print();


    }

    public static class MyFlatMap implements FlatMapFunction<String, String> {

        @Override
        public void flatMap(String value, Collector<String> out) throws Exception {
            String[] arr = value.split(" ");
            for (int i = 0; i < arr.length; i++) {
                out.collect(arr[i]);
            }
        }
    }


}
